---
title: "Android Development Fundamentals"
description: "Learn Android development with Kotlin, comparing with JavaScript mobile development patterns and React Native concepts"
---

# Android Development Fundamentals

Welcome to the sixth module of JavaScript to Kotlin conversion! In this module, we'll explore Android development with Kotlin and understand how it compares to JavaScript mobile development patterns like React Native. We'll learn about Android project structure, Activity lifecycle, UI components, and modern Android development practices.

## Learning Objectives

By the end of this module, you will be able to:
- Understand Android project structure and architecture
- Compare Android development with React Native patterns
- Implement Activity lifecycle management
- Create and manage Fragments effectively
- Design responsive layouts with XML and Compose
- Handle user interactions and events
- Manage Android resources and assets
- Apply modern Android development best practices

## Android Project Structure

### Project Organization

Android projects have a specific structure that differs significantly from JavaScript/React Native projects. Let's explore the key differences.

<UniversalEditor title="Project Structure Comparison" compare={true}>
```javascript !! js
// React Native project structure
// App.js - Main application component
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

// HomeScreen.js - Screen component
import React, { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

const HomeScreen = ({ navigation }) => {
  const [count, setCount] = useState(0);
  
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Welcome to React Native</Text>
      <Text style={styles.counter}>Count: {count}</Text>
      <Button 
        title="Increment" 
        onPress={() => setCount(count + 1)} 
      />
      <Button 
        title="Go to Details" 
        onPress={() => navigation.navigate('Details')} 
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  counter: {
    fontSize: 18,
    marginBottom: 20,
  },
});

export default HomeScreen;
```

```kotlin !! kt
// Android project structure
// MainActivity.kt - Main activity
package com.example.myapp

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyAppTheme {
                val navController = rememberNavController()
                
                NavHost(navController = navController, startDestination = "home") {
                    composable("home") { HomeScreen(navController) }
                    composable("details") { DetailsScreen(navController) }
                }
            }
        }
    }
}

// HomeScreen.kt - Screen composable
@Composable
fun HomeScreen(navController: NavController) {
    var count by remember { mutableStateOf(0) }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = "Welcome to Android",
            style = MaterialTheme.typography.headlineMedium,
            modifier = Modifier.padding(bottom = 16.dp)
        )
        
        Text(
            text = "Count: $count",
            style = MaterialTheme.typography.bodyLarge,
            modifier = Modifier.padding(bottom = 16.dp)
        )
        
        Button(
            onClick = { count++ },
            modifier = Modifier.padding(bottom = 8.dp)
        ) {
            Text("Increment")
        }
        
        Button(
            onClick = { navController.navigate("details") }
        ) {
            Text("Go to Details")
        }
    }
}
```
</UniversalEditor>

### Directory Structure

Let's examine the typical Android project directory structure and compare it with React Native.

<UniversalEditor title="Directory Structure" compare={true}>
```javascript !! js
// React Native project structure
my-react-native-app/
├── App.js                 // Main app component
├── package.json           // Dependencies and scripts
├── src/
│   ├── components/        // Reusable components
│   ├── screens/          // Screen components
│   ├── navigation/       // Navigation configuration
│   ├── services/         // API calls and business logic
│   └── utils/            // Helper functions
├── assets/               // Images, fonts, etc.
└── android/              // Android-specific files
    └── app/
        └── src/
            └── main/
                ├── java/  // Native Android code
                └── res/   // Android resources
```

```kotlin !! kt
// Android project structure
my-android-app/
├── app/
│   ├── build.gradle.kts  // Module-level build config
│   └── src/
│       ├── main/
│       │   ├── java/     // Kotlin/Java source code
│       │   │   └── com/example/myapp/
│       │   │       ├── MainActivity.kt
│       │   │       ├── ui/           // UI components
│       │   │       ├── data/         // Data layer
│       │   │       ├── domain/       // Business logic
│       │   │       └── utils/        // Helper functions
│       │   ├── res/      // Android resources
│       │   │   ├── layout/           // XML layouts
│       │   │   ├── values/           // Strings, colors, dimensions
│       │   │   ├── drawable/         // Images and drawables
│       │   │   └── menu/             // Menu resources
│       │   └── AndroidManifest.xml   // App configuration
│       ├── test/         // Unit tests
│       └── androidTest/  // Instrumented tests
├── build.gradle.kts      // Project-level build config
└── settings.gradle.kts   // Project settings
```
</UniversalEditor>

## Activity Lifecycle

### Understanding Activity Lifecycle

Android Activities have a well-defined lifecycle that's crucial for proper app behavior. This is different from React Native's component lifecycle.

<UniversalEditor title="Activity Lifecycle" compare={true}>
```javascript !! js
// React Native component lifecycle
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';

const MyComponent = () => {
  const [data, setData] = useState(null);
  
  // Component mount (equivalent to onCreate)
  useEffect(() => {
    console.log('Component mounted');
    fetchData();
    
    // Component unmount (equivalent to onDestroy)
    return () => {
      console.log('Component unmounting');
      cleanup();
    };
  }, []);
  
  // Component update (equivalent to onResume/onPause)
  useEffect(() => {
    console.log('Component updated');
  });
  
  const fetchData = async () => {
    try {
      const response = await fetch('https://api.example.com/data');
      const result = await response.json();
      setData(result);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };
  
  const cleanup = () => {
    // Cleanup resources
    console.log('Cleaning up resources');
  };
  
  return (
    <View>
      <Text>{data ? JSON.stringify(data) : 'Loading...'}</Text>
    </View>
  );
};
```

```kotlin !! kt
// Android Activity lifecycle
class MainActivity : AppCompatActivity() {
    private var data: String? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        Log.d("MainActivity", "onCreate called")
        fetchData()
    }
    
    override fun onStart() {
        super.onStart()
        Log.d("MainActivity", "onStart called")
    }
    
    override fun onResume() {
        super.onResume()
        Log.d("MainActivity", "onResume called")
        // App becomes visible and interactive
    }
    
    override fun onPause() {
        super.onPause()
        Log.d("MainActivity", "onPause called")
        // App loses focus but is still visible
    }
    
    override fun onStop() {
        super.onStop()
        Log.d("MainActivity", "onStop called")
        // App is no longer visible
    }
    
    override fun onDestroy() {
        super.onDestroy()
        Log.d("MainActivity", "onDestroy called")
        cleanup()
    }
    
    private fun fetchData() {
        lifecycleScope.launch {
            try {
                val response = URL("https://api.example.com/data").readText()
                data = response
                updateUI()
            } catch (error: Exception) {
                Log.e("MainActivity", "Error fetching data", error)
            }
        }
    }
    
    private fun updateUI() {
        // Update UI with data
        findViewById<TextView>(R.id.textView).text = data ?: "Loading..."
    }
    
    private fun cleanup() {
        // Cleanup resources
        Log.d("MainActivity", "Cleaning up resources")
    }
}
```
</UniversalEditor> 

## Fragment Management

### Understanding Fragments

Fragments are reusable UI components in Android that can be combined to create flexible layouts. This concept is similar to React Native components but with different lifecycle management.

<UniversalEditor title="Fragment Implementation" compare={true}>
```javascript !! js
// React Native component (equivalent to Fragment)
import React, { useState, useEffect } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

const UserProfileComponent = ({ userId, onUserUpdate }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    fetchUserData(userId);
  }, [userId]);
  
  const fetchUserData = async (id) => {
    try {
      setLoading(true);
      const response = await fetch(`https://api.example.com/users/${id}`);
      const userData = await response.json();
      setUser(userData);
    } catch (error) {
      console.error('Error fetching user:', error);
    } finally {
      setLoading(false);
    }
  };
  
  const handleUpdateUser = () => {
    onUserUpdate(user);
  };
  
  if (loading) {
    return (
      <View style={styles.container}>
        <Text>Loading user data...</Text>
      </View>
    );
  }
  
  return (
    <View style={styles.container}>
      <Text style={styles.title}>{user?.name}</Text>
      <Text style={styles.email}>{user?.email}</Text>
      <Button title="Update User" onPress={handleUpdateUser} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 16,
    backgroundColor: '#f5f5f5',
    borderRadius: 8,
    margin: 8,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  email: {
    fontSize: 14,
    color: '#666',
    marginBottom: 16,
  },
});

export default UserProfileComponent;
```

```kotlin !! kt
// Android Fragment implementation
class UserProfileFragment : Fragment() {
    private var userId: String? = null
    private var onUserUpdateListener: ((User) -> Unit)? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            userId = it.getString("user_id")
        }
    }
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_user_profile, container, false)
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        userId?.let { id ->
            fetchUserData(id)
        }
    }
    
    private fun fetchUserData(userId: String) {
        lifecycleScope.launch {
            try {
                val response = URL("https://api.example.com/users/$userId").readText()
                val user = parseUserFromJson(response)
                updateUI(user)
            } catch (error: Exception) {
                Log.e("UserProfileFragment", "Error fetching user", error)
            }
        }
    }
    
    private fun updateUI(user: User) {
        view?.findViewById<TextView>(R.id.userName)?.text = user.name
        view?.findViewById<TextView>(R.id.userEmail)?.text = user.email
        
        view?.findViewById<Button>(R.id.updateButton)?.setOnClickListener {
            onUserUpdateListener?.invoke(user)
        }
    }
    
    fun setOnUserUpdateListener(listener: (User) -> Unit) {
        onUserUpdateListener = listener
    }
    
    companion object {
        fun newInstance(userId: String): UserProfileFragment {
            return UserProfileFragment().apply {
                arguments = Bundle().apply {
                    putString("user_id", userId)
                }
            }
        }
    }
}

// Fragment layout: fragment_user_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp"
    android:background="@drawable/fragment_background">
    
    <TextView
        android:id="@+id/userName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textStyle="bold"
        android:layout_marginBottom="8dp"/>
    
    <TextView
        android:id="@+id/userEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="#666666"
        android:layout_marginBottom="16dp"/>
    
    <Button
        android:id="@+id/updateButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Update User"/>
        
</LinearLayout>
```
</UniversalEditor>

## Layout and UI Components

### XML Layouts vs React Native Styles

Android uses XML layouts for UI design, while React Native uses JavaScript styles. Let's compare these approaches.

<UniversalEditor title="Layout Comparison" compare={true}>
```javascript !! js
// React Native layout with styles
import React from 'react';
import { View, Text, StyleSheet, ScrollView } from 'react-native';

const ProductList = ({ products }) => {
  return (
    <ScrollView style={styles.container}>
      {products.map((product, index) => (
        <View key={index} style={styles.productCard}>
          <Text style={styles.productTitle}>{product.name}</Text>
          <Text style={styles.productPrice}>${product.price}</Text>
          <Text style={styles.productDescription}>{product.description}</Text>
        </View>
      ))}
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    padding: 16,
  },
  productCard: {
    backgroundColor: 'white',
    borderRadius: 8,
    padding: 16,
    marginBottom: 12,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
  },
  productTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 8,
    color: '#333',
  },
  productPrice: {
    fontSize: 16,
    color: '#007AFF',
    fontWeight: '600',
    marginBottom: 8,
  },
  productDescription: {
    fontSize: 14,
    color: '#666',
    lineHeight: 20,
  },
});

export default ProductList;
```

```kotlin !! kt
// Android XML layout equivalent
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_light"
    android:padding="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/productRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>

    </LinearLayout>
</ScrollView>

<!-- Product item layout: item_product.xml -->
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="12dp"
    app:cardCornerRadius="8dp"
    app:cardElevation="5dp"
    app:cardBackgroundColor="@color/white">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp">

        <TextView
            android:id="@+id/productTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:textStyle="bold"
            android:textColor="@color/text_primary"
            android:layout_marginBottom="8dp"/>

        <TextView
            android:id="@+id/productPrice"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="16sp"
            android:textColor="@color/primary_blue"
            android:textStyle="bold"
            android:layout_marginBottom="8dp"/>

        <TextView
            android:id="@+id/productDescription"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            android:textColor="@color/text_secondary"
            android:lineSpacingExtra="4dp"/>

    </LinearLayout>
</androidx.cardview.widget.CardView>

// Kotlin adapter for RecyclerView
class ProductAdapter(
    private val products: List<Product>,
    private val onProductClick: (Product) -> Unit
) : RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() {

    class ProductViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val title: TextView = view.findViewById(R.id.productTitle)
        val price: TextView = view.findViewById(R.id.productPrice)
        val description: TextView = view.findViewById(R.id.productDescription)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_product, parent, false)
        return ProductViewHolder(view)
    }

    override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
        val product = products[position]
        holder.title.text = product.name
        holder.price.text = "$${product.price}"
        holder.description.text = product.description
        
        holder.itemView.setOnClickListener {
            onProductClick(product)
        }
    }

    override fun getItemCount() = products.size
}
```
</UniversalEditor>

## Event Handling and User Interactions

### Touch Events and Gestures

Android provides comprehensive touch event handling that's more granular than React Native's gesture system.

<UniversalEditor title="Event Handling" compare={true}>
```javascript !! js
// React Native touch handling
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, PanGestureHandler } from 'react-native';
import { GestureHandlerRootView } from 'react-native-gesture-handler';

const TouchExample = () => {
  const [touchCount, setTouchCount] = useState(0);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  
  const handlePress = () => {
    setTouchCount(prev => prev + 1);
  };
  
  const handleLongPress = () => {
    console.log('Long press detected');
  };
  
  const handlePanGesture = (event) => {
    setPosition({
      x: event.nativeEvent.translationX,
      y: event.nativeEvent.translationY,
    });
  };
  
  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <TouchableOpacity
          onPress={handlePress}
          onLongPress={handleLongPress}
          style={{
            padding: 20,
            backgroundColor: '#007AFF',
            borderRadius: 8,
          }}
        >
          <Text style={{ color: 'white', fontSize: 16 }}>
            Touch Count: {touchCount}
          </Text>
        </TouchableOpacity>
        
        <PanGestureHandler onGestureEvent={handlePanGesture}>
          <View style={{
            width: 100,
            height: 100,
            backgroundColor: '#FF3B30',
            borderRadius: 50,
            transform: [{ translateX: position.x }, { translateY: position.y }],
          }} />
        </PanGestureHandler>
      </View>
    </GestureHandlerRootView>
  );
};

export default TouchExample;
```

```kotlin !! kt
// Android touch handling
class TouchExampleActivity : AppCompatActivity() {
    private var touchCount = 0
    private var position = PointF(0f, 0f)
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_touch_example)
        
        setupTouchHandling()
    }
    
    private fun setupTouchHandling() {
        val touchButton = findViewById<Button>(R.id.touchButton)
        val draggableView = findViewById<View>(R.id.draggableView)
        
        // Simple touch handling
        touchButton.setOnClickListener {
            touchCount++
            touchButton.text = "Touch Count: $touchCount"
        }
        
        // Long press handling
        touchButton.setOnLongClickListener {
            Log.d("TouchExample", "Long press detected")
            true // Consume the event
        }
        
        // Custom touch handling for draggable view
        draggableView.setOnTouchListener { view, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    // Store initial touch position
                    position.x = event.rawX - view.x
                    position.y = event.rawY - view.y
                    true
                }
                MotionEvent.ACTION_MOVE -> {
                    // Update view position
                    view.x = event.rawX - position.x
                    view.y = event.rawY - position.y
                    true
                }
                MotionEvent.ACTION_UP -> {
                    // Handle touch release
                    Log.d("TouchExample", "Touch released at (${view.x}, ${view.y})")
                    true
                }
                else -> false
            }
        }
    }
}

// Gesture detection with GestureDetector
class GestureExampleActivity : AppCompatActivity() {
    private lateinit var gestureDetector: GestureDetector
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gesture_example)
        
        setupGestureDetection()
    }
    
    private fun setupGestureDetection() {
        val gestureView = findViewById<View>(R.id.gestureView)
        
        gestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
            override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
                Log.d("GestureExample", "Single tap detected")
                return true
            }
            
            override fun onDoubleTap(e: MotionEvent): Boolean {
                Log.d("GestureExample", "Double tap detected")
                return true
            }
            
            override fun onLongPress(e: MotionEvent) {
                Log.d("GestureExample", "Long press detected")
            }
            
            override fun onFling(
                e1: MotionEvent?,
                e2: MotionEvent,
                velocityX: Float,
                velocityY: Float
            ): Boolean {
                Log.d("GestureExample", "Fling detected: vx=$velocityX, vy=$velocityY")
                return true
            }
        })
        
        gestureView.setOnTouchListener { _, event ->
            gestureDetector.onTouchEvent(event)
        }
    }
}
```
</UniversalEditor>

## Resource Management

### Android Resources vs React Native Assets

Android uses a comprehensive resource system, while React Native uses a simpler asset approach.

<UniversalEditor title="Resource Management" compare={true}>
```javascript !! js
// React Native asset management
import React from 'react';
import { View, Text, Image, StyleSheet } from 'react-native';

const AssetExample = () => {
  return (
    <View style={styles.container}>
      <Image 
        source={require('./assets/logo.png')}
        style={styles.logo}
        resizeMode="contain"
      />
      
      <Text style={styles.title}>Welcome to React Native</Text>
      
      <View style={styles.buttonContainer}>
        <Text style={styles.button}>Primary Button</Text>
        <Text style={styles.secondaryButton}>Secondary Button</Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
    padding: 20,
  },
  logo: {
    width: 120,
    height: 120,
    marginBottom: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 30,
  },
  buttonContainer: {
    flexDirection: 'row',
    gap: 10,
  },
  button: {
    backgroundColor: '#007AFF',
    color: 'white',
    padding: 12,
    borderRadius: 8,
    fontSize: 16,
    fontWeight: '600',
  },
  secondaryButton: {
    backgroundColor: '#6c757d',
    color: 'white',
    padding: 12,
    borderRadius: 8,
    fontSize: 16,
    fontWeight: '600',
  },
});

export default AssetExample;
```

```kotlin !! kt
// Android resource management
// strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">My Android App</string>
    <string name="welcome_message">Welcome to Android</string>
    <string name="primary_button">Primary Button</string>
    <string name="secondary_button">Secondary Button</string>
</resources>

// colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primary_blue">#007AFF</color>
    <color name="secondary_gray">#6C757D</color>
    <color name="background_light">#F5F5F5</color>
    <color name="text_primary">#333333</color>
    <color name="white">#FFFFFF</color>
</resources>

// dimensions.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="logo_size">120dp</dimen>
    <dimen name="title_size">24sp</dimen>
    <dimen name="button_padding">12dp</dimen>
    <dimen name="corner_radius">8dp</dimen>
</resources>

// activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:background="@color/background_light"
    android:padding="20dp">

    <ImageView
        android:id="@+id/logoImage"
        android:layout_width="@dimen/logo_size"
        android:layout_height="@dimen/logo_size"
        android:src="@drawable/logo"
        android:scaleType="fitCenter"
        android:layout_marginBottom="20dp"/>

    <TextView
        android:id="@+id/titleText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/welcome_message"
        android:textSize="@dimen/title_size"
        android:textStyle="bold"
        android:textColor="@color/text_primary"
        android:layout_marginBottom="30dp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/primaryButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/primary_button"
            android:background="@drawable/button_primary"
            android:textColor="@color/white"
            android:padding="@dimen/button_padding"
            android:layout_marginEnd="8dp"/>

        <Button
            android:id="@+id/secondaryButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/secondary_button"
            android:background="@drawable/button_secondary"
            android:textColor="@color/white"
            android:padding="@dimen/button_padding"
            android:layout_marginStart="8dp"/>

    </LinearLayout>

</LinearLayout>

// MainActivity.kt
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        setupButtons()
    }
    
    private fun setupButtons() {
        findViewById<Button>(R.id.primaryButton).setOnClickListener {
            // Handle primary button click
            Toast.makeText(this, "Primary button clicked", Toast.LENGTH_SHORT).show()
        }
        
        findViewById<Button>(R.id.secondaryButton).setOnClickListener {
            // Handle secondary button click
            Toast.makeText(this, "Secondary button clicked", Toast.LENGTH_SHORT).show()
        }
    }
}
```
</UniversalEditor>

## Modern Android Development Practices

### Jetpack Compose vs Traditional Views

Jetpack Compose represents the modern approach to Android UI development, similar to React Native's declarative style.

<UniversalEditor title="Modern UI Development" compare={true}>
```javascript !! js
// React Native declarative UI
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';

const ModernUIExample = () => {
  const [isExpanded, setIsExpanded] = useState(false);
  const [selectedItems, setSelectedItems] = useState([]);
  
  const toggleExpanded = () => {
    setIsExpanded(!isExpanded);
  };
  
  const toggleItem = (itemId) => {
    setSelectedItems(prev => 
      prev.includes(itemId) 
        ? prev.filter(id => id !== itemId)
        : [...prev, itemId]
    );
  };
  
  return (
    <View style={styles.container}>
      <TouchableOpacity 
        style={styles.header} 
        onPress={toggleExpanded}
      >
        <Text style={styles.headerText}>
          {isExpanded ? '▼' : '▶'} Modern UI Example
        </Text>
      </TouchableOpacity>
      
      {isExpanded && (
        <View style={styles.content}>
          {['Item 1', 'Item 2', 'Item 3'].map((item, index) => (
            <TouchableOpacity
              key={index}
              style={[
                styles.item,
                selectedItems.includes(index) && styles.selectedItem
              ]}
              onPress={() => toggleItem(index)}
            >
              <Text style={styles.itemText}>{item}</Text>
            </TouchableOpacity>
          ))}
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    margin: 16,
    backgroundColor: 'white',
    borderRadius: 8,
    overflow: 'hidden',
  },
  header: {
    padding: 16,
    backgroundColor: '#007AFF',
  },
  headerText: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
  content: {
    padding: 16,
  },
  item: {
    padding: 12,
    marginVertical: 4,
    backgroundColor: '#f8f9fa',
    borderRadius: 6,
  },
  selectedItem: {
    backgroundColor: '#e3f2fd',
    borderColor: '#007AFF',
    borderWidth: 1,
  },
  itemText: {
    fontSize: 16,
  },
});

export default ModernUIExample;
```

```kotlin !! kt
// Jetpack Compose declarative UI
@Composable
fun ModernUIExample() {
    var isExpanded by remember { mutableStateOf(false) }
    var selectedItems by remember { mutableStateOf(setOf<Int>()) }
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column {
            // Header
            Surface(
                modifier = Modifier.fillMaxWidth(),
                color = MaterialTheme.colorScheme.primary,
                onClick = { isExpanded = !isExpanded }
            ) {
                Row(
                    modifier = Modifier.padding(16.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = if (isExpanded) "▼" else "▶",
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onPrimary
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "Modern UI Example",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.onPrimary
                    )
                }
            }
            
            // Content
            AnimatedVisibility(
                visible = isExpanded,
                enter = expandVertically() + fadeIn(),
                exit = shrinkVertically() + fadeOut()
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    listOf("Item 1", "Item 2", "Item 3").forEachIndexed { index, item ->
                        Surface(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 2.dp),
                            color = if (index in selectedItems) 
                                MaterialTheme.colorScheme.primaryContainer
                            else 
                                MaterialTheme.colorScheme.surface,
                            shape = RoundedCornerShape(6.dp),
                            onClick = {
                                selectedItems = if (index in selectedItems) {
                                    selectedItems - index
                                } else {
                                    selectedItems + index
                                }
                            }
                        ) {
                            Text(
                                text = item,
                                modifier = Modifier.padding(12.dp),
                                style = MaterialTheme.typography.bodyLarge
                            )
                        }
                    }
                }
            }
        }
    }
}

// State management with ViewModel
class ModernUIViewModel : ViewModel() {
    private val _uiState = MutableStateFlow(ModernUIState())
    val uiState: StateFlow<ModernUIState> = _uiState.asStateFlow()
    
    fun toggleExpanded() {
        _uiState.value = _uiState.value.copy(
            isExpanded = !_uiState.value.isExpanded
        )
    }
    
    fun toggleItemSelection(itemId: Int) {
        val currentSelection = _uiState.value.selectedItems.toMutableSet()
        if (itemId in currentSelection) {
            currentSelection.remove(itemId)
        } else {
            currentSelection.add(itemId)
        }
        _uiState.value = _uiState.value.copy(selectedItems = currentSelection)
    }
}

data class ModernUIState(
    val isExpanded: Boolean = false,
    val selectedItems: Set<Int> = emptySet()
)

// Activity using Compose
class ModernUIActivity : ComponentActivity() {
    private val viewModel: ModernUIViewModel by viewModels()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyAppTheme {
                val uiState by viewModel.uiState.collectAsState()
                
                ModernUIExample(
                    isExpanded = uiState.isExpanded,
                    selectedItems = uiState.selectedItems,
                    onToggleExpanded = { viewModel.toggleExpanded() },
                    onToggleItem = { viewModel.toggleItemSelection(it) }
                )
            }
        }
    }
}
```
</UniversalEditor>

## Summary

In this module, we've explored the fundamentals of Android development with Kotlin and compared them with JavaScript/React Native patterns. Here are the key takeaways:

### Key Concepts Covered:
1. **Project Structure**: Android's organized directory structure vs React Native's simpler approach
2. **Lifecycle Management**: Activity and Fragment lifecycles vs React component lifecycles
3. **UI Development**: XML layouts and Compose vs React Native's StyleSheet approach
4. **Event Handling**: Android's comprehensive touch system vs React Native's gesture handling
5. **Resource Management**: Android's resource system vs React Native's asset approach
6. **Modern Practices**: Jetpack Compose's declarative UI vs React Native's component-based approach

### Android Development Advantages:
- **Type Safety**: Kotlin's strong type system prevents runtime errors
- **Performance**: Native Android performance vs JavaScript bridge overhead
- **Platform Integration**: Direct access to Android APIs and system features
- **Tooling**: Excellent IDE support with Android Studio
- **Ecosystem**: Rich Android-specific libraries and frameworks

### Best Practices:
1. **Use Jetpack Compose** for modern UI development
2. **Implement proper lifecycle management** to prevent memory leaks
3. **Follow Material Design guidelines** for consistent user experience
4. **Use ViewModels** for state management and configuration changes
5. **Implement proper error handling** and user feedback
6. **Optimize for performance** with RecyclerView and efficient layouts

### Next Steps:
In the next module, we'll explore Web development with Kotlin, including Spring Boot frameworks and backend services, continuing our journey from JavaScript to Kotlin development patterns. 